package cn.com.wxUtil;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.com.constant.Code;
import cn.com.util.JsonUtil;

public class SendTemplateMessageUtil {
	public static void send(String jsonTemplate) throws Exception {
		// 1.获取access_token 成功!
		String urls = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConstant.APPID
				+ "&secret=" + wxConstant.SECRET;
		URL templateUrl = new URL(urls);
		String json = cn.com.util.HttpUtil.doGet(templateUrl);
		JSONObject jsonObject = JSON.parseObject(json);
		String access_token = (String) jsonObject.get("access_token");
		if (StringUtils.isEmpty(access_token)) {
			System.out.println(jsonObject.get("errmsg"));
		}
		// 2.调用模板消息发送接口
		urls = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;
		try {
			String postData = cn.com.wxUtil.HttpUtil.postData(urls, jsonTemplate);
			JSONObject parseObject = JSON.parseObject(postData);
			String errcode = parseObject.get("errcode").toString();
			if (!errcode.equals("0")) {
				throw new Exception(parseObject.get("errcode")+":"+parseObject.get("errmsg"));
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
}
